﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Globalization;

namespace CoolCode.Web.Mvc
{
    public static class ControllerExtensions
    {
        public static bool ContainsKey(this System.Web.Mvc.ControllerBase controller, string key)
        {
            return controller.ValueProvider.GetValue(key) != null;
        }

		public static T ValueOf<T>(this System.Web.Mvc.ControllerBase controller, string key)
		{ 
			return controller.ValueOf(key, default(T));
		}

        public static T ValueOf<T>(this System.Web.Mvc.ControllerBase controller, string key, T defaultValue)
        {
            if (controller.ControllerContext.RouteData.Values.ContainsKey(key) &&
                controller.ControllerContext.RouteData.Values[key] !=(object) string.Empty )
            {
                object value= controller.ControllerContext.RouteData.Values[key];
                return (T)Convert.ChangeType(value, typeof(T), CultureInfo.CurrentUICulture);
            }

            ValueProviderResult result = controller.ValueProvider.GetValue(key);

            if (result != null && result.RawValue != (object)string.Empty)
            {
                return (T)result.ConvertTo(typeof(T), CultureInfo.CurrentUICulture);
            }

            return defaultValue;
        }

        public static T AttemptedValueOf<T>(this System.Web.Mvc.ControllerBase controller, string key)
        {
            ValueProviderResult result = controller.ValueProvider.GetValue(key);

            if (result != null && !string.IsNullOrEmpty(result.AttemptedValue))
            {
                return (T)Convert.ChangeType(result.AttemptedValue, typeof(T), CultureInfo.CurrentUICulture);
            }

            return default(T);
        }
    }
}
